<template>
<section class="container">
  <div class="row">
    <div class="col-md-9">
      <h1>标题：{{ topic.title }}</h1>
      <p> 发布于 3 年前  作者 j60017268  5730 次浏览  最后一次编辑是 2 年前  来自 问答</p>
      <p v-if="isLoginUser">
        <router-link :to="{name:'topic-edit',params:{id:topic.id}}">编辑</router-link>
        <a @click.prevent="removeTopicById(topic.id)" href="#">删除</a>
      </p>
      <hr/>
      <article class="markdown-body">
      {{ topic.content }}
    </article>
      <div class="panel panel-default" v-for="comment in comments">
        <div class="panel-heading">
          <span>lipengzhou</span> commented 
          <span>24 minutes ago</span>
          <span class="action">
            <a href=""><i class="glyphicon glyphicon-thumbs-up pull-right"></i></a>
            <a href=""><i class="glyphicon glyphicon-remove-circle pull-right"></i></a>
            <a href=""><i class="glyphicon glyphicon-remove-circle pull-right"></i></a>
          </span>
        </div>
        <div class="panel-body">{{ comment.content }}</div>
      </div>
      <hr>
      <form @submit.prevent="addCommentHandler">
        <div class="form-group">
          <label for="addComm">添加回复</label>
          <textarea class="form-control" v-model="commentContent" id="addComm" rows="3"></textarea>
        </div>
        <button type="submit" class="btn btn-success">回复</button>
      </form>
    </div>
  </div>
</section>
</template>

<script>
import axios from 'axios'

export default {
	data () {
		return {
      topic : {
        title : '',
        content : ''
      },
      commentContent : '',
      comments : [],
      // 编辑和删除默认是不显示的，只有话题属于当前登录用户才显示
      isLoginUser : false
    }
	},
  created () {
    const {id} = this.$route.params
    this.loadTopicById(id)
    this.loadCommentsByTopicId(id)
  },
  // 路由导航钩子
  // to 当前路由信息
  // from 从哪个组件到货过来的路由信息
  // next 导航完成，渲染组件
  // 
  // 暂时先不使用
  // async beforeRouteEnter (to, from, next) {
  //   // 在渲染该组件的对应路由被 confirm 前调用
  //   // 不！能！获取组件实例 `this`
  //   // 因为当守卫执行前，组件实例还没被创建
  //   const {id} = to.params
  //   const {data : topic} = await axios.get(`/api/topics/${id}`)
  //   const {data : sessionUser} = await axios.get('/api/session')
  //   next(vm => {
  //     vm.topic = topic
  //     vm.isLoginUser = topic.user_id === sessionUser.id
  //   })
  // },
  methods : {
    async addCommentHandler () {
      if ( ! this.isLoginUser) {
        if ( ! window.confirm('请先登录')) {
          return
        }
        return this.$router.push('/login')
      }
      try {
        const {data:comment} = await axios.post('/api/comments', {
          content:this.commentContent,
          topic_id : this.topic.id
        })
        this.comments.unshift(comment)
        this.commentContent = ''
      } catch(err) {
        const {status, statusText, data} = err.response
        switch (status) {
          case 401:
            window.alert('没有登陆，请先登录')
            break;
          default:
            window.alert(status + '|' + statusText)
            break;
        }
        
      }
    },
    async loadTopicById (id) {
      try {
        const {data : topic} = await axios.get(`/api/topics/${id}`)
        this.topic = topic

        // 获取当前会话状态信息
        const {data : sessionUser} = await axios.get('/api/session')
        if (topic.user_id === sessionUser.id) {
          this.isLoginUser = true
        }
      } catch(err) {
        // console.log(err.resqonse)
        // const {status} = err.resqonse
        // switch (status) {
        //   case 500:
        //     console.log('服务器错误');  
        //     break
        // }
      }
    },
    async loadCommentsByTopicId (topic_id) {
      try {
        const {data : comments} = await axios.get(`/api/comments?topic_id=${topic_id}`)
        this.comments = comments
      } catch(err) {
        // console.log(err)
        const {status, statusText, data} = err.response
        console.log(status + '|' + statusText)
      }
    },
    async removeTopicById (id) {
      if ( ! window.confirm('确定要删除吗？')) {
        return
      }
      try {
        // console.log(id)
        const ret = await axios.delete(`/api/topics/${id}`)
        this.$router.push('/')
      } catch(err) {
        const {status, statusText, data} = err.response
        console.log(status + '|' + statusText)
      }
    }
  }
}
</script>

<style>
.markdown-body{margin-bottom: 100px;}
</style>
